/**
 * 账户数据访问服务
 */
const fs = require('fs').promises;
const { USER_ACCOUNTS_FILE, ADMIN_ACCOUNTS_FILE } = require('../utils/constants');

/**
 * 读取用户账号
 */
async function readUserAccounts() {
    try {
        const data = await fs.readFile(USER_ACCOUNTS_FILE, 'utf-8');
        return JSON.parse(data);
    } catch (error) {
        // 如果文件不存在，返回默认账号
        const defaultAccounts = {
            accounts: [
                {
                    id: 'user-default',
                    username: '123',
                    password: '123',
                    name: '默认用户',
                    createdAt: new Date().toISOString(),
                    lastLogin: null,
                    isDefault: true
                }
            ]
        };
        await saveUserAccounts(defaultAccounts);
        return defaultAccounts;
    }
}

/**
 * 保存用户账号
 */
async function saveUserAccounts(data) {
    await fs.writeFile(USER_ACCOUNTS_FILE, JSON.stringify(data, null, 2), 'utf-8');
}

/**
 * 读取管理员账号
 */
async function readAdminAccounts() {
    try {
        const data = await fs.readFile(ADMIN_ACCOUNTS_FILE, 'utf-8');
        return JSON.parse(data);
    } catch (error) {
        // 如果文件不存在，返回默认管理员账号
        const defaultAdmins = {
            accounts: [
                {
                    id: 'admin-default',
                    username: 'admin',
                    password: 'admin',
                    name: '默认管理员',
                    role: 'super-admin',
                    createdAt: new Date().toISOString(),
                    lastLogin: null,
                    isDefault: true
                }
            ]
        };
        await saveAdminAccounts(defaultAdmins);
        return defaultAdmins;
    }
}

/**
 * 保存管理员账号
 */
async function saveAdminAccounts(data) {
    await fs.writeFile(ADMIN_ACCOUNTS_FILE, JSON.stringify(data, null, 2), 'utf-8');
}

module.exports = {
    readUserAccounts,
    saveUserAccounts,
    readAdminAccounts,
    saveAdminAccounts
};

